package com.zeng.ssm.service.support.async;

import com.zeng.ssm.util.TraceNoUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * 线程-TraceNo包装工具类
 *
 * @author zengwanlin
 * @date 2023-04-03T14:17
 */
public class ThreadTraceNoUtil {

    public static Runnable wrap(final Runnable task) {
        if (task == null) {
            throw new IllegalArgumentException("线程任务不能为空");
        }
        final String parentTraceNo = TraceNoUtil.getTraceNo();
        return new Runnable() {
            @Override
            public void run() {
                if (StringUtils.isEmpty(parentTraceNo)) {
                    TraceNoUtil.newTraceNo();
                } else {
                    TraceNoUtil.newTraceNo(parentTraceNo);
                }
                try {
                    task.run();
                } finally {
                    TraceNoUtil.clearTraceNo();
                }
            }
        };
    }

}
